package com.sunxy.bluetoothdemo.net

import android.text.TextUtils
import android.util.ArrayMap
import com.common.frame.net.RetrofitManager
import com.common.frame.utils.GsonUtils
import com.common.frame.utils.LogUtils
import com.common.frame.utils.RequestUtils
import com.common.frame.utils.TransformUtils
import com.sunxy.bluetoothdemo.bean.BlueDeviceBean
import io.reactivex.SingleObserver
import io.reactivex.disposables.Disposable

/**
 *
 * create by sunxy on 2021/3/24
 **/
class MainInteractor {

    private fun getApiService() = RetrofitManager.manager.apiService

    fun upload(bean: BlueDeviceBean, callback: (BlueDeviceBean)->Unit) {
                val map = ArrayMap<String, Any>()
        map["beaconName"] = bean.beaconName
        map["major"] = bean.major
        map["minor"] = bean.minor
        map["bluetoothAddress"] = bean.bluetoothAddress
        map["txPower"] = bean.txPower
        map["rssi"] = bean.rssi
        getApiService().upload(RequestUtils.paramsToRequestBody(map))
            .compose(TransformUtils.defaultSingleSchedulers())
            .subscribe(object: SingleObserver<String>{
                override fun onSubscribe(d: Disposable) {
                    LogUtils.e("onSubscribe")
                }

                override fun onSuccess(t: String) {
                    LogUtils.e("onSuccess: $t")
                    bean.status = if (TextUtils.equals("Success", t)) 2 else 0
                    callback?.invoke(bean)
                }

                override fun onError(e: Throwable) {
                    LogUtils.e("onError: " + e.message)
                    bean.status = 0
                    callback?.invoke(bean)
                    e.printStackTrace()
                }

            })
    }

    fun upload(bean: MutableList<BlueDeviceBean>) {
        val map = ArrayMap<String, Any>()
        map["imei"] = "132123"
        map["beacons"] = bean
        getApiService().uploads(RequestUtils.paramsToRequestBody(map))
            .compose(TransformUtils.defaultSingleSchedulers())
            .subscribe(object: SingleObserver<String>{
                override fun onSubscribe(d: Disposable) {
                    LogUtils.e("onSubscribe")
                }

                override fun onSuccess(t: String) {
                    LogUtils.e("onSuccess: $t")
                }

                override fun onError(e: Throwable) {
                    LogUtils.e("onError: " + e.message)
                    e.printStackTrace()
                }

            })
    }
}